<template>
  <div>
    <form ref="form" method="post" enctype="multipart/form-data">
      <input name="token" type="hidden" :value="token">
      <input v-if="clearFile" name="file" :id="pickerId" type="file" @change="upload" :accept="accept" capture="camera" :multiple="multiple"/>
      <input name="accept" type="hidden"/>
      <slot name="form"></slot>
    </form>
    <label :for="pickerId">
      <slot name="picker">
        <em>upload</em>
      </slot>
    </label>
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    props: {
      method: {
        type: String,
        default: 'post'
      },
      action: {
        type: String,
        default: 'http://upload.qiniu.com'
      },
      token: {
        type: String,
        default: ''
      },
      accept: {
        type: String,
        default: 'image/png, image/jpeg, image/gif'
      },
      multiple: {
        type: Boolean,
        default: false
      },
      callback: {
        type: Function,
        default: () => {
          // console.log('upload done');
        }
      }
    },
    data () {
      return {
        pickerId: `picker${new Date().getTime()}`,
        clearFile: true
      }
    },
    mounted () {
    },
    methods: {
      // 清除File
      clearFiles () {
        this.clearFile = false
        setTimeout(() => {
          this.clearFile = true
        }, 20)
      },
      upload () {
        let formData = new FormData(this.$refs.form)
        if (this.multiple) {
          let files = formData.getAll('file')
          formData.set('file', files[0])
          axios.post(this.action, formData).then(res => {
            this.$emit('upload', res.data)
            this.clearFiles()
          })
        } else {
          axios.post(this.action, formData).then(res => {
            this.$emit('upload', res.data)
            this.clearFiles()
          })
        }
      }
    },
    components: {}
  }
</script>

<style lang="scss" scoped>
  form {
    display: none;
  }
</style>
